--[=[
    雪月框架 - Builder  --- 入口
]=]

--从 package.path 中提取转化出当前目录

--Root = xxxxxx\XG_Framework  后面不带\
--UTF8编码

Root = package.path:sub(1, package.path:find("\\w3x2lni\\bin",3,true)-1  )
--F:\F-drive\Project\闆湀\XG_Framework\w3x2lni\bin\lua\?.lua
--F:\F-drive\Project\闆湀\XG_Framework

package.path = Root .. '\\w3x2lni\\script\\?.lua'
package.path = package.path .. ';'..Root ..'\\?.lua;'
package.path = package.path .. ';'..Root ..'\\?\\init.lua'
package.path = package.path .. ';'..Root ..'\\compiler\\?.lua'


unicode = require 'ffi.unicode'
ini = require 'module.ini'
require 'module.api'



require 'builder'
print('----雪月框架 - Builder----')
print("当前时间:", os.date("%Y-%m-%d   %H:%M:%S",os.time()))


--build 表 存放 生成所需的参数

builder.args = arg --运行参数
builder.map = '' --maps中地图文件夹名字[项目名字]  默认为UTF8
builder.type = '' --编译方式:debug/release/encryption/obfuscation 分别对应 测试/正式/加密/加密混淆
builder.cfg = ini:open(Root .. '\\config.ini')
builder.ydPath = arg[1]

if builder.ydPath == '' then
    --CMD传参失败！
    --尝试从bat中手动读取
    local list = dir_list(Root .. '\\*.bat')
    for index, filename in ipairs(list) do
        local file = io.open( Root .. '\\' .. filename, "r")
        if file then
            local bat = file:read('a')
            file:close()
            builder.ydPath = bat:match('([A-z]:.-)\r?\n'):lighter()
        end
    end
else
    builder.ydPath = builder.ydPath:lighter():u2a()
end

if builder.ydPath:sub(-1) == '\\' then
    builder.ydPath = builder.ydPath:sub(1,-2)
end



--[[----------------------
在绘画GUI之前可以先检测参数
如果 项目名字、编译方式 参数齐全的情况
可以直接跳过GUI进入编译步骤]]

TYPE = {
    last = '最后编译的结果',
    obfuscation = 'SLK+混淆',
    slk = 'SLK优化',
    test = '测试版',
    debug = '调试版',
}

TYPE_id = { --按钮顺序，同时对应TYPE表的名字
    'debug',
    'test',
    'slk',
    'obfuscation',
    'last',
}

if type(arg[2]) == 'string'  then
    if arg[2] ~= '' then
        builder.map =  arg[2]
    end
end
if type(arg[3]) == 'string'  then
    if arg[3] ~= '' then
        builder.type = arg[3]
    end
end

if builder.map ~= '' and builder.type ~= '' then
    print(">>>跳过GUI 进入编译过程>>>")
    builder:exec()
    return  --取消GUI的创建
end

--[[----------------------]]

local gui = require 'yue.gui'
local ext = require 'yue-ext'
local timer = require 'gui.timer'
local ev = require 'gui.event'
local ui = require 'gui.new.template'
local fs = require 'bee.filesystem'

local window = {}
fs.path()
builder.window = window

ext.on_timer = timer.update
function ext.on_dropfile(filename)
    if window._worker and not window._worker.exited then
        return
    end
    -- xxxx.xxx
    local file = filename:sub( filename:find_r('\\')+1 )
    --文件名 不含后缀
    local name = file:sub( 1, file:find_r('%.')-1 )
    --后缀
    local suffix = file:sub( -4 )
    print(  ('接受拖拽文件 [ %s ]'):format(file)  )

    if suffix ~= '.w3x' then
        print( 'error\t拖入的不是w3x地图文件' )
        return
    end
    
    print('正在生成项目,请稍候...')

    local output = Root .. '\\maps\\'.. name
    local temp = Root .. '\\debug\\' ..  name  .. '\\temp'

    mkdir( output ) --创建输出目录
    mkdir( temp ) --创建temp目录

    _print( w2l('lni', filename:u2a(), output:u2a()) ) --显示解包进度

    --xcopy( output, temp )
    --delete(temp..'\\*.lua')
    --w2l('obj', temp:u2a(), output:u2a() .. '\\Terrain.w3x')

    copy(filename, output .. '\\Terrain.w3x')

    --rd(temp)
    print( '如果w3x2lni发生错误则说明你的地图不支持,或许是因为特殊的触发器UI' )
    print( '<自动关闭界面 请重新打开刷新项目>' )
    mkdir( output .. '\\scripts' )
    local f = io.open( output .. '\\scripts\\Main.lua' , 'a+')--创建空文件
    if f then f:close()  end
    print( ('>项目文件夹: %s'):format(output) )
    print( ('>为你创建了Lua入口文件: %s\\scripts\\Main.lua'):format(output) )
    window._window:close()
end


local function create_mainview(win)
    local template = ui.container {
        color = '#222',
        style = { Padding = 1 },
        ui.container {
            id = 'caption',
            style = { Height = 40, FlexDirection = 'row', JustifyContent = 'space-between' },
            bind = {
                color = 'theme'
            },
            ui.label {
                id = 'title',
                style = { Width = 200 },
                align = 'start',
                font = { name = 'Constantia', size = 24, weight = 'bold' },
                bind = {
                    text = 'title'
                }
            },
            ui.container {
                id = 'close',
                style = { Margin = 0, Width = 40 },
                color_hover = '#BE3246',
                bind = {
                    color = 'theme'
                }
            }
        }
    }
    
    local view, data, element = ui.create(template, {
        title = 'W3x2Lni',
        theme = '#00ADD9',
    })
    
    ev.on('update theme', function(color, title)
        data.theme = color
        data.title = title
    end)
    
    element.caption:setmousedowncanmovewindow(true)
    element.title:setmousedowncanmovewindow(true)

    function element.close:onmousedown()
        win:close()
    end
    local canvas = gui.Canvas.createformainscreen{width=40, height=40}
    local painter = canvas:getpainter()
    painter:setstrokecolor('#000000')
    painter:beginpath()
    painter:moveto(15, 15)
    painter:lineto(25, 25)
    painter:moveto(15, 25)
    painter:lineto(25, 15)
    painter:closepath()
    painter:stroke()
    function element.close:ondraw(painter, dirty)
        painter:drawcanvas(canvas, {x=0, y=0, width=40, height=40})
    end
    return view
end

function window:create(t)
    local win = gui.Window.create { frame = false }
    function win.onclose()
        gui.MessageLoop.quit()
    end
    win:settitle('雪月框架 - Builder')
    ext.register_window('雪月框架 - Builder')
    ext.set_icon((fs.exe_path():parent_path() / 'w3x2lni.ico'):string())
    win:sethasshadow(true)
    win:setresizable(false)
    win:setmaximizable(false)
    win:setminimizable(false)
    win:setcontentview(create_mainview(win))
    win:setcontentsize { width = t.width, height = t.height }
    win:center()
    win:activate()
    self._window = win
end

function window:set_theme(title, color)
    self._color = color
    ev.emit('update theme', color, title)
end

function window:show_page(name)
    local view = self._window:getcontentview()
    if self._page then
        self._page:setvisible(false)
    end
    self._page = require('page.' .. name)
    self._page:setvisible(true)
    view:addchildview(self._page)
    if self._page.on_show then
        self._page:on_show()
    end
end

local view = window:create {
    width = 350, 
    height = 400,
}

window:set_theme('雪月框架 - Builder  v'.. builder.ver, '#00ADD9')
window:show_page('index')

gui.MessageLoop.run()


--%ydwePath%\bin\YDWEConfig.exe -launchwar3 -loadfile "%ydwePath%\%mapName%.w3x"